//
//  Custom_ZHTool.m
//  FootPad
//
//  Created by 张浩 on 2021/3/18.
//  Copyright © 2021 hb_147. All rights reserved.
//

#import "Custom_ZHTool.h"
#import <AVFoundation/AVFoundation.h>

@implementation Custom_ZHTool

//包装常用控件创建方式，以便提高代码简洁性
+(id)uiButtonCreate:(UIColor*)backcolor Text:(NSString*)text TextColor:(UIColor *)textColor TextFont:(UIFont*)textFont Image:(UIImage*)image{
    UIButton *btn = [[UIButton alloc]init];
    if (backcolor) {
        [btn setBackgroundColor:backcolor];
    }
    if (text) {
        [btn setTitle:text forState:UIControlStateNormal];
    }
    if (textColor) {
        [btn setTitleColor:textColor forState:UIControlStateNormal];
    }
    if (textFont) {
        btn.titleLabel.font = textFont;
    }
    if (image){
        [btn setImage:image forState:UIControlStateNormal];
    }
    
    return btn;
}
// fontsize 为负数表示粗体
+(id)uiLabelCreate:(NSString*)text Frame:(CGRect)frame Font:(UIFont*)font TextColor:(UIColor*)textcolor  {
    
    UILabel *lab = [[UILabel alloc]initWithFrame:frame];
    
    if (text) {
        [lab setText:text];
    }
    if (textcolor) {
        [lab setTextColor:textcolor];
    }
    if(font){
        lab.font = font;
    }
    return lab;
}
// fontsize 为负数表示粗体
+(id)uiLabelCreate:(NSString*)text Font:(UIFont*)font TextColor:(UIColor*)textcolor  {
    
    UILabel *lab = [[UILabel alloc]init];
    
    if (text) {
        [lab setText:text];
    }
    if (textcolor) {
        [lab setTextColor:textcolor];
    }
    if(font){
        lab.font = font;
    }
    return lab;
}

#pragma mark ----------------    获取文字size      ------------------
/* 获得文本的具体size**/
+ (CGSize)getTextSizeWithFont:(UIFont *)font text:(NSString *)text maxWidth:(CGFloat)maxWidth {
    
    if (font == nil || text.length == 0) {
        return CGSizeZero;
    }
    
    CGSize textSize = [text boundingRectWithSize:CGSizeMake(maxWidth, MAXFLOAT)
                                         options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
                                      attributes:@{NSFontAttributeName: font}
                                         context:nil].size;
    /* 多一个像素 防止有中文的时候 计算不准确 **/
    textSize.height += 1;
    return textSize;
    
}

/* 获取单行中的size **/
+ (CGSize)getTextSizeWithFont:(UIFont *)font text:(NSString *)text {
    
    return [Custom_ZHTool getTextSizeWithFont:font text:text maxWidth:CGFLOAT_MAX];
}



#pragma mark ----------------    图片      ------------------
/**
 压缩图片
 
 @param sourceImage 要处理的图片
 @param targetWidth 比例
 @return 处理好的
 */
+ (UIImage *)compressForWidthOfImage:(UIImage *)sourceImage targetWidth:(CGFloat)targetWidth {
    
    CGSize imageSize = sourceImage.size;
    CGFloat width  = imageSize.width;
    CGFloat height = imageSize.height;
    if (targetWidth>width || sourceImage == nil) {
        return sourceImage;
    }else {
        CGFloat targetHeight = (targetWidth/width) * height;
        UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
        [sourceImage drawInRect:CGRectMake(0,0,targetWidth, targetHeight)];
        UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return newImage;
    }
}

/**获取当前时间**/
+(NSString *)getCurrentTimeStr {
    
    NSString *dateStr = @"";
    
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    dateStr = [formatter stringFromDate:[NSDate date]];
    return dateStr;
}

/**获取当前时间到小时**/
+(NSString *)getCurrentTimeStr_MM {
    
    NSString *dateStr = @"";
    
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm"];
    dateStr = [formatter stringFromDate:[NSDate date]];
    return dateStr;
}

//计算 中英文混合 字符数；
+(int)convertToInt:(NSString*)strtemp {
    
    int strlength = 0;
    char* p = (char*)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding];
    for (int i=0 ; i<[strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {
        if (*p) {
            p++;
            strlength++;
        }
        else {
            p++;
        }
    }
    return strlength;
    
}
+(NSMutableAttributedString *)createAttributedStringWithString:(NSString *)string key:(NSString *)key fontSize:(CGFloat)fontSize keyColor:(UIColor *)color {
    if (string == nil) {
        return [[NSMutableAttributedString alloc] initWithString:@""];
    }
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string];
    if (key != nil) {
        NSRange range = [string rangeOfString:key];
        if (range.location != NSNotFound) {
            [attrString addAttribute:NSForegroundColorAttributeName value:color range:range];
            [attrString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:fontSize] range:range];
        }
    }
    return attrString;
}

+(NSMutableAttributedString *)createAttributedStringWithString:(NSString *)string key:(NSString *)key keyFont:(UIFont *)font keyColor:(UIColor *)color {
    if (string == nil) {
        return [[NSMutableAttributedString alloc] initWithString:@""];
    }
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string];
    NSRange range = [string rangeOfString:key];
    if (range.location != NSNotFound) {
        [attrString addAttribute:NSForegroundColorAttributeName value:color range:range];
        [attrString addAttribute:NSFontAttributeName value:font range:range];
    }
    return attrString;
}

/**
 取指定的日期显示
 
 @param dateStr 后台返回的YYYY-MM-dd HH:mm:ss格式的日期Str
 @param format @"YYYY-MM-dd HH:mm:ss"
 @return 日期
 */
NSString *getCustomDateStr(NSString *dateStr,NSString *format) {
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    
    NSDate *resDate = [formatter dateFromString:dateStr];
    
    NSDateFormatter * lastFormat = [[NSDateFormatter alloc]init];
    
    [lastFormat setDateFormat:format];
    
    return [lastFormat stringFromDate:resDate];
}
/**
 取指定的日期显示转年月日时分秒
 
 @param dateStr 后台返回的YYYY-MM-dd HH:mm:ss格式的日期Str
 @param format @"yyyy年MM月dd日 HH时mm分ss秒"
 @return 日期
 */
NSString *getChineseDateStr(NSString *dateStr,NSString *format) {
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    
    NSDate *resDate = [formatter dateFromString:dateStr];
    
    NSDateFormatter * lastFormat = [[NSDateFormatter alloc]init];
    
    
    [lastFormat setDateFormat:format];
    
    return [lastFormat stringFromDate:resDate];
}
/**
 开启一个定时器
 
 @param target 定时器持有者
 @param timeInterval 执行间隔时间
 @param handler 重复执行事件
 
 调用 dispatch_source_cancel(timer); 就会将 timer 对象销毁，唯一要考虑的就是 timer 的结束时机；即使你不主动释放timer， 也不会造成循环引用哦 O(∩_∩)O~
 */
void dispatchTimer(id target, double timeInterval,void (^handler)(dispatch_source_t timer))
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer =dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0, 0, queue);
    dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), (uint64_t)(timeInterval *NSEC_PER_SEC), 0);
    // 设置回调
    __weak __typeof(target) weaktarget  = target;
    dispatch_source_set_event_handler(timer, ^{
        if (!weaktarget)  {
            dispatch_source_cancel(timer);
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (handler) handler(timer);
            });
        }
    });
    // 启动定时器
    dispatch_resume(timer);
}
/**
 获取视频的第一帧图片
 
 @param videoURL 视频的本地路径
 @param time 获取时间一般是0.01
 @return 图片
 */
+ (UIImage*)thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    CFTimeInterval thumbnailImageTime = time;
    NSError *thumbnailImageGenerationError = nil;
    CGImageRef thumbnailImageRef  = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60) actualTime:NULL error:&thumbnailImageGenerationError];
    
    UIImage *thumbnailImage = thumbnailImageRef?[UIImage imageWithCGImage:thumbnailImageRef]:nil;
    CGImageRelease(thumbnailImageRef);
    
    return thumbnailImage;
    //    return nil;
}

//秒转多少分钟多少秒
+(NSString *)getMMSSFromSS:(NSString *)totalTime{
    
    NSInteger seconds = [totalTime integerValue];
    //minute
    NSInteger minute = seconds/60;
    //second
    NSInteger second = seconds%60;
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%02ld:%02ld",(long)minute,(long)second];
    return format_time;
}

//毫秒转化为时分秒
+(NSString *)getWhenVehicleSS:(NSString *)msTime {
    
    if (!stringIsEmpty(msTime)) {
        
        NSTimeInterval timerInterval = [msTime doubleValue];
        
        NSInteger timeout = timerInterval/1000;
        NSInteger hours = (NSInteger)timeout / 3600;
        NSInteger minute = (NSInteger) (timeout / 60) % 60;
//        NSInteger second = (NSInteger)timeout % 60;
        return [NSString stringWithFormat:@"%ld小时%ld分钟",hours,minute];
    }
    return @"";
}

+ (BOOL)textFieldIsPrice:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    //限制只能输入数字
    BOOL isHaveDian = YES;
    if ([string isEqualToString:@" "]) {
        return NO;
    }
    if ([textField.text rangeOfString:@"."].location == NSNotFound) {
        isHaveDian = NO;
    }
    if ([string length] > 0) {
        unichar single = [string characterAtIndex:0];//当前输入的字符
        if ((single >= '0' && single <= '9') || single == '.') {
            //数据格式正确
            if([textField.text length] == 0){
                if(single == '.') {
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            }
            //输入的字符是否是小数点
            if (single == '.') {
                if(!isHaveDian) {
                    //text中还没有小数点
                    isHaveDian = YES;
                    return YES;
                }else{
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            }else{
                //存在小数点
                if (isHaveDian) {
                    //判断小数点的位数，2 代表位数，可以
                    NSRange ran = [textField.text rangeOfString:@"."];
                    if (range.location - ran.location <= 2) {
                        return YES;
                    }else{
                        return NO;
                    }
                }else{
                    return YES;
                }
            }
        }else{
            //输入的数据格式不正确
            [textField.text stringByReplacingCharactersInRange:range withString:@""];
            return NO;
        }
    }
    return YES;

}

//取整数 取余数
+ (NSArray *)exceptActionString:(NSString *)string1 andString:(NSString *)string2 {
    
    NSMutableArray *numberArray = [NSMutableArray array];
    
    //整除
    NSInteger number = 0;
    NSString *str1;
    NSInteger remainder = 0;

    //判断除数的长度是否比被除数长
    if(string1.length >= string2.length){
        
        for(int i = 0; i < string1.length - (string2.length -1);i++){
            
            if (i > 0) {
                
                //取出下一次运算的数据
                str1 = [string1 substringWithRange:NSMakeRange(i + string2.length -1,1)];
                
                if (remainder != 0) {
                    //把余数 和 下一次运算的数据取出 组成新的除数
                    str1 = [NSString stringWithFormat:@"%ld%@",(long)remainder,str1];
                }
                
            }else{
                //取出第一次运算的除数
                str1 = [string1 substringWithRange:NSMakeRange(i, string2.length)];
            }
            
            //整除
            if ([str1 integerValue] >0 && [string2 integerValue]) {
                number = [str1 integerValue]/[string2 integerValue];
            }else {
                number = 0;
            }
            
            if ([str1 integerValue] >0 && [string2 integerValue]) {
                //取余
                remainder = [str1 integerValue]%[string2 integerValue];
            }else {
                remainder = 0;
            }
            
            [numberArray insertObject:[NSString stringWithFormat:@"%ld",(long)number] atIndex:i];
        }
        
        //去掉无效的0
        if (numberArray.count > 0) {

            NSInteger i = 0;
            
            while (i < numberArray.count -1) {
                
                NSString *str1 = numberArray[0];
                
                if ([str1 integerValue] == 0) {
                    //去掉无效的0
                    [numberArray removeObjectAtIndex:i];
                }else{
                    break;
                }
                i++;
            }
        }
        
        NSString *string = [numberArray componentsJoinedByString:@""];
        
        NSArray *arr = @[string,[NSString stringWithFormat:@"%ld",(long)remainder]];
        return arr;
        
    }else {
        return @[@"0",@"0"];
    }
}

//取整数 取余数
+ (NSArray *)exceptBatchActionString:(NSString *)string1 andString:(NSString *)string2 {
    
    NSMutableArray *numberArray = [NSMutableArray array];
    
    //整除
    NSInteger number = 0;
    NSString *str1;
    NSInteger remainder = 0;

    //判断除数的长度是否比被除数长
    if(string1.length >= string2.length){
        
        for(int i = 0; i < string1.length - (string2.length -1);i++){
            
            if (i > 0) {
                
                //取出下一次运算的数据
                str1 = [string1 substringWithRange:NSMakeRange(i + string2.length -1,1)];
                
                if (remainder != 0) {
                    //把余数 和 下一次运算的数据取出 组成新的除数
                    str1 = [NSString stringWithFormat:@"%ld%@",(long)remainder,str1];
                }
                
            }else{
                //取出第一次运算的除数
                str1 = [string1 substringWithRange:NSMakeRange(i, string2.length)];
            }
            
            //整除
            if ([str1 integerValue] >0 && [string2 integerValue]) {
                number = [str1 integerValue]/[string2 integerValue];
            }else {
                number = 0;
            }
            
            if ([str1 integerValue] >0 && [string2 integerValue]) {
                //取余
                remainder = [str1 integerValue]%[string2 integerValue];
            }else {
                remainder = 0;
            }
            
            [numberArray insertObject:[NSString stringWithFormat:@"%ld",(long)number] atIndex:i];
        }
        
        //去掉无效的0
        if (numberArray.count > 0) {

            NSInteger i = 0;
            
            while (i < numberArray.count -1) {
                
                NSString *str1 = numberArray[0];
                
                if ([str1 integerValue] == 0) {
                    //去掉无效的0
                    [numberArray removeObjectAtIndex:i];
                }else{
                    break;
                }
                i++;
            }
        }
        
        NSString *string = [numberArray componentsJoinedByString:@""];
        
        NSArray *arr = @[string,[NSString stringWithFormat:@"%ld",(long)remainder]];
        return arr;
        
    }else {
                
        return @[@"0",string1];
    }
}

//获取当前年
+ (NSString *)getCurrentYear {
        
    NSDate *date = [NSDate date];
//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    //下面是单独获取每项的值
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSCalendarUnitYear |NSCalendarUnitMonth |NSCalendarUnitDay |NSCalendarUnitWeekday |NSCalendarUnitHour |NSCalendarUnitMinute |NSCalendarUnitSecond;
    comps = [calendar components:unitFlags fromDate:date];
    //年
    NSInteger year =[comps year];
    
    return @(year).description;
}
//获取当前月
+ (NSString *)getCurrentMonth {
    
    NSDate *date = [NSDate date];
//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    //下面是单独获取每项的值
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSCalendarUnitYear |NSCalendarUnitMonth |NSCalendarUnitDay |NSCalendarUnitWeekday |NSCalendarUnitHour |NSCalendarUnitMinute |NSCalendarUnitSecond;
    comps = [calendar components:unitFlags fromDate:date];

    //月
    NSInteger month = [comps month];
    
    if (month <= 9) {
        return [NSString stringWithFormat:@"%0ld",month];
    }
    return @(month).description;
}
//获取当前日
+ (NSString *)getCurrentDay {
    
    NSDate *date = [NSDate date];
//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    //下面是单独获取每项的值
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSCalendarUnitYear |NSCalendarUnitMonth |NSCalendarUnitDay |NSCalendarUnitWeekday |NSCalendarUnitHour |NSCalendarUnitMinute |NSCalendarUnitSecond;
    comps = [calendar components:unitFlags fromDate:date];
    //日
    NSInteger day = [comps day];
    
    if (day <= 9) {
        return [NSString stringWithFormat:@"%0ld",day];
    }
    return @(day).description;
}

//数字转化汉子
+ (NSString *)translationChinese:(NSString *)numberStr {
    
    NSString *str = [NSString stringWithFormat:@"%ld",(long)numberStr.integerValue];
    NSArray *arabic_numerals = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0"];
    NSArray *chinese_numerals = @[@"一",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"零"];
    NSArray *digits = @[@"个",@"十",@"百",@"千",@"万",@"十",@"百",@"千",@"亿",@"十",@"百",@"千",@"兆"];
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:chinese_numerals forKeys:arabic_numerals];
    NSMutableArray *sums = [NSMutableArray array];
    
    for (int i = 0; i < str.length; i ++) {
        NSString *substr = [str substringWithRange:NSMakeRange(i, 1)];
        NSString *a = [dictionary objectForKey:substr];
        NSString *b = digits[str.length -i-1];
        NSString *sum = [a stringByAppendingString:b];
        if ([a isEqualToString:chinese_numerals[9]]) {
            
            if([b isEqualToString:digits[4]] || [b isEqualToString:digits[8]])
            {
                sum = b;
                if ([[sums lastObject] isEqualToString:chinese_numerals[9]])
                {
                    [sums removeLastObject];
                }
                
            }else {
                sum = chinese_numerals[9];
            }
            if ([[sums lastObject] isEqualToString:sum]) {
                continue;
            }
            
        }
        [sums addObject:sum];
    }
    NSString *sumStr = [sums componentsJoinedByString:@""];
    if (str.length == 2) {
        NSComparisonResult result1 = [str compare:@"09"];
        NSComparisonResult result2 = [str compare:@"20"];
        if (result1 == 1 && result2 == -1) {
            sumStr = [sumStr substringFromIndex:1];
            
        }
        
    }
    NSString *chinese = [sumStr substringToIndex:sumStr.length-1];
    return chinese;
    
}

+ (UIImage *)creatQRImage:(NSString *)url withSize:(CGFloat)size {
    //创建过滤器
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    //过滤器恢复默认
    [filter setDefaults];
    //给过滤器添加数据
    NSString *string = url;
    //将NSString格式转化成NSData格式
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    [filter setValue:data forKeyPath:@"inputMessage"];
    //获取二维码过滤器生成的二维码
    CIImage *img= [filter outputImage];
    //将获取到的二维码添加到imageview上
    return [self setQRImage:img withSize:size];
}

+ (UIImage *)setQRImage:(CIImage *)image withSize:(CGFloat)size {
    
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

/**
 *  判断两个版本的大小
 *
 *  @param version1 第一比较的版本
 *  @param version2 第二个比较的版本
 *
 *  @return 返回两个版本的比较
 
 version1 > version2 返回 1
 version1 < version2 返回 -1
 version1 = version2 返回 0
 */
+ (NSInteger)versionCompareResultWithversion1:(NSString *)version1 version2:(NSString *)version2 {
    
    if (version1 == nil || version2 == nil) {
        
        if (version2) {
            return -1;
        }
        if (version1) {
            return 1;
        }
        return 0;
    }else { // version1 和 version2 都是有值的
        
        NSArray * version1Arr = [version1 componentsSeparatedByString:@"."];
        NSArray * version2Arr = [version2 componentsSeparatedByString:@"."];
        
        NSInteger count = version1Arr.count > version2Arr.count?version2Arr.count:version1Arr.count;
        
        for (NSInteger i = 0; i<count; i++) {
            NSInteger version1ItemValue = [version1Arr[i] integerValue];
            NSInteger version2ItemValue = [version2Arr[i] integerValue];
            if (version1ItemValue > version2ItemValue) {
                return 1;
            }else if(version1ItemValue < version2ItemValue){
                return -1;
            }else {
                continue;
            }
        }
        
        //如果前面没有判断出来，就只能判断个数
        
        if (version1Arr.count > version2Arr.count) {
            return 1;
        }else if (version1Arr.count < version2Arr.count){
            return -1;
        }else {
            return 0;
        }
    }
    return 0;
}

//处理服务器丢失精度问题
+ (NSString *)precisionLossNumber:(NSString *)numberStr {
        
    if ([numberStr isKindOfClass:[NSString class]] && [numberStr containsString:@"."]) {
        NSString *valueStr = [NSString stringWithFormat:@"%lf",numberStr.doubleValue];
        NSDecimalNumber *deciNumber = [[NSDecimalNumber alloc] initWithString:valueStr];
        return deciNumber.stringValue;
    }
    return numberStr;
}

/// 特殊符号
+ (NSString *)specialSymbolsAction {
    //数学符号
    NSString *matSym = @" ﹢﹣×÷±/=≌∽≦≧≒﹤﹥≈≡≠=≤≥<>≮≯∷∶∫∮∝∞∧∨∑∏∪∩∈∵∴⊥∥∠⌒⊙√∟⊿㏒㏑%‰⅟½⅓⅕⅙⅛⅔⅖⅚⅜¾⅗⅝⅞⅘≂≃≄≅≆≇≈≉≊≋≌≍≎≏≐≑≒≓≔≕≖≗≘≙≚≛≜≝≞≟≠≡≢≣≤≥≦≧≨≩⊰⊱⋛⋚∫∬∭∮∯∰∱∲∳%℅‰‱øØπ";
    //标点符号
    NSString *punSym = @"。，、＇：∶；?‘’“”〝〞ˆˇ﹕︰﹔﹖﹑·¨….¸;！´？！～—ˉ｜‖＂〃｀@﹫¡¿﹏﹋﹌︴々﹟#﹩$﹠&﹪%*﹡﹢﹦﹤‐￣¯―﹨ˆ˜﹍﹎+=<＿_-ˇ~﹉﹊（）〈〉‹›﹛﹜『』〖〗［］《》〔〕{}「」【】︵︷︿︹︽_﹁﹃︻︶︸﹀︺︾ˉ﹂﹄︼❝❞!():,'[]｛｝^・.·．•＃＾＊＋＝＼＜＞＆§⋯`－–／—|\"\\";
    //单位符号＊·
    NSString *unitSym = @"°′″＄￥〒￠￡％＠℃℉﹩﹪‰﹫㎡㏕㎜㎝㎞㏎³㎎㎏㏄º○¤%$º¹²³";
    //货币符号
    NSString *curSym = @"₽€£Ұ₴$₰¢₤¥₳₲₪₵元₣₱฿¤₡₮₭₩ރ円₢₥₫₦ł﷼₠₧₯₨Kčर₹ƒ₸￠";
    //制表符
    NSString *tabSym = @"─ ━│┃╌╍╎╏┄ ┅┆┇┈ ┉┊┋┌┍┎┏┐┑┒┓└ ┕┖┗ ┘┙┚┛├┝┞┟┠┡┢┣ ┤┥┦┧┨┩┪┫┬ ┭ ┮ ┯ ┰ ┱ ┲ ┳ ┴ ┵ ┶ ┷ ┸ ┹ ┺ ┻┼ ┽ ┾ ┿ ╀ ╁ ╂ ╃ ╄ ╅ ╆ ╇ ╈ ╉ ╊ ╋ ╪ ╫ ╬═║╒╓╔ ╕╖╗╘╙╚ ╛╜╝╞╟╠ ╡╢╣╤ ╥ ╦ ╧ ╨ ╩ ╳╔ ╗╝╚ ╬ ═ ╓ ╩ ┠ ┨┯ ┷┏ ┓┗ ┛┳ ⊥ ﹃ ﹄┌ ╮ ╭ ╯╰";
    
    return [NSString stringWithFormat:@"%@%@%@%@%@",matSym,punSym,unitSym,curSym,tabSym];
}

//处理手机号
+ (NSString *)getPhoneDesc:(NSString *)phoneStr {
    
    NSString *phone = phoneStr;
    
    if (phoneStr.description.length >= 11) {
        
        NSString *string=[phoneStr stringByReplacingOccurrencesOfString:[phoneStr substringWithRange:NSMakeRange(3,4)]withString:@"****"];
        phone = phoneStr;
    }
    return phone;
}

+ (NSString *)getVideoSizeMPath:(NSURL *)filUrl {
    
    // 此类主要用于获取媒体信息，包括视频、声音等
    AVURLAsset *asset = [AVURLAsset assetWithURL:filUrl];
    // 方法会根据指定的媒体类型返回一个track数组，数组中包含着Asset中所有指定媒体类型的track。
    // 如果Asset中没有这个媒体类型的track，返回一个空数组。
    NSArray<AVAssetTrack *> *tracks = [asset tracksWithMediaType:AVMediaTypeVideo];

    NSString *descStr = @"";
    CGSize videoSize;
    for (AVAssetTrack *track in tracks) {
        
        if([track.mediaType isEqualToString:AVMediaTypeVideo])
        {
            if (track.totalSampleDataLength >= 1048576) {//1048576bt = 1M  小于1m的显示KB 大于1m显示M
                descStr = [NSString stringWithFormat:@"%.2lldM",track.totalSampleDataLength/1024/1024];
            } else {
                descStr = [NSString stringWithFormat:@"%.1lldKB",track.totalSampleDataLength/1024];
            }
            videoSize = track.naturalSize;
            
        }
    }

    NSLog(@"descStrdescStrdescStrdescStr == %@ videoSizevideoSizevideoSizevideoSizevideoSize == %fW ===== %fH",descStr,videoSize.width,videoSize.height);
    return descStr;
}

/** 设置缩放动画 */
+ (void)startScaleAnimation:(UIView *)view andDuration:(CGFloat)duration CGAScaleX:(CGFloat)ScaleX CGAScaleY:(CGFloat)ScaleY {
    
//    [self.backAnimaImageView setNeedsLayout];
//    [self.backAnimaImageView layoutIfNeeded];
//    [self.imageView setNeedsLayout];
//    [self.imageView layoutIfNeeded];

    // 放大动画
    [UIView animateWithDuration:duration animations:^{
        view.transform = CGAffineTransformMakeScale(ScaleX, ScaleY); //等比放大1.2倍
    } completion:^(BOOL finished) {
        // 缩回去动画
        [UIView animateWithDuration:duration animations:^{
//            view.transform = CGAffineTransformMakeScale(0.01, 0.01); //等比放大1.2倍
            view.transform = CGAffineTransformIdentity; //回复原始状态
        } completion:^(BOOL finished) {
            // 放大动画
//            [UIView animateWithDuration:0.08 animations:^{
//                view.transform = CGAffineTransformMakeScale(1.2, 1.2); //等比放大1.1倍
//            } completion:^(BOOL finished) {
//                // 缩回去动画
//                [UIView animateWithDuration:0.04 animations:^{
//                    view.transform = CGAffineTransformIdentity; //回复原始状态
//                }];
//            }];
        }];
    }];
}

//比较两个时间相差多少天 用来弹闲机弹窗
+ (NSInteger)compareTime:(NSString *)fristTime andEndtime:(NSString *)endTime {
    
    if (!stringIsEmpty(fristTime) && !stringIsEmpty(endTime)) {
        
        
        //创建两个日期
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
        [dateFormatter setDateFormat:@"YYYY-MM-dd"];

        NSDate *startDate = [dateFormatter dateFromString:getCustomDateStr(fristTime, @"YYYY-MM-dd")];
        NSDate *endDate = [dateFormatter dateFromString:getCustomDateStr(endTime, @"YYYY-MM-dd")];
        NSTimeInterval timeZoneOffset = [[NSTimeZone systemTimeZone] secondsFromGMT];
        startDate = [startDate dateByAddingTimeInterval:timeZoneOffset];
        endDate = [endDate dateByAddingTimeInterval:timeZoneOffset];

        //利用NSCalendar比较日期的差异
        NSCalendar *calendar = [NSCalendar currentCalendar];
        /**
         * 要比较的时间单位,常用如下,可以同时传：
         *    NSCalendarUnitDay : 天
         *    NSCalendarUnitYear : 年
         *    NSCalendarUnitMonth : 月
         *    NSCalendarUnitHour : 时
         *    NSCalendarUnitMinute : 分
         *    NSCalendarUnitSecond : 秒
         */
        NSCalendarUnit unit = NSCalendarUnitDay;//只比较天数差异
        //比较的结果是NSDateComponents类对象
        NSDateComponents *delta = [calendar components:unit fromDate:startDate toDate:endDate options:0];
        //打印
        NSLog(@"%@",delta);
        //获取其中的"天"
        NSLog(@"%ld",delta.day);
        
        return delta.day;
    }
    return 0;
}

//比较两个时间相差多少秒 用来判断弹窗
+ (NSInteger)comSecondspareTime:(NSString *)fristTime andEndtime:(NSString *)endTime {
    
    if (!stringIsEmpty(fristTime) && !stringIsEmpty(endTime)) {
        
        //创建两个日期
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
        [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];

        NSDate *startDate = [dateFormatter dateFromString:getCustomDateStr(fristTime, @"YYYY-MM-dd HH:mm:ss")];
        NSDate *endDate = [dateFormatter dateFromString:getCustomDateStr(endTime, @"YYYY-MM-dd HH:mm:ss")];
        NSTimeInterval timeZoneOffset = [[NSTimeZone systemTimeZone] secondsFromGMT];
        startDate = [startDate dateByAddingTimeInterval:timeZoneOffset];
        endDate = [endDate dateByAddingTimeInterval:timeZoneOffset];

        //利用NSCalendar比较日期的差异
        NSCalendar *calendar = [NSCalendar currentCalendar];
        /**
         * 要比较的时间单位,常用如下,可以同时传：
         *    NSCalendarUnitDay : 天
         *    NSCalendarUnitYear : 年
         *    NSCalendarUnitMonth : 月
         *    NSCalendarUnitHour : 时
         *    NSCalendarUnitMinute : 分
         *    NSCalendarUnitSecond : 秒
         */
        NSCalendarUnit unit = NSCalendarUnitSecond;//只比较秒数差异
        //比较的结果是NSDateComponents类对象
        NSDateComponents *delta = [calendar components:unit fromDate:startDate toDate:endDate options:0];
        //打印
        NSLog(@"%@",delta);
        //获取其中的"天"
        NSLog(@"%ld",delta.second);
        
        return delta.second;
    }
    return 0;
}

+ (BOOL)checkIsAllNumberWithString:(NSString *)string {
    
    BOOL res = YES;
    NSCharacterSet *tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < string.length) {
        NSString *str = [string substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [str rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

@end
